<?php

namespace backend\modules\business\controllers;

use common\models\BusConfig;
use common\models\BusMemberBeautycard;
use common\models\BusService;
use Yii;
use common\models\BusAccount;
use common\models\BusMember;
use common\models\BusHealth;
use common\models\BusMemberHealth;
use common\models\BusMemberConsume;
use common\models\BusBeautycardMemory;
use yii\data\Pagination;
use yii\helpers\Url;

// 会员控制器
class MemberController extends \backend\controllers\BaseController
{
    /**
     * 档案列表
     */
    public function actionIndex($sort = '', $key = '', $type = '', $birthday = '')
    {
        switch ($sort) { // 排序方式
            case 'consume':
                $order = 'consume_amount_all DESC';
                break;
            case 'last':
                $order = 'last_consume_time';
                break;
            default:
                $order = 'member_id';
        }

        $model = BusMember::find()->select(['bus_member.*', '(sum(cash_pay) + sum(unionpay)) consume_amount_all'])->where(['bus_member.shop_id' => $this->userInfo->shop_id, 'del_flag' => 1]);
        if ($key) { // 会员名、手机号码检索
            if (is_numeric($key)) {
                $model->andWhere(['like', 'member_mobile', $key]);
            } else {
                $model->andWhere(['like', 'member_name', $key]);
            }
        }
        if ($type && $type != 'all') { // 会员类型检索
            $model->andWhere(['member_grade' => $type]);
        }
        if ($birthday) {
            $model->andWhere(['member_birthday' => $birthday]);
        }

        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 11, 'defaultPageSize' => 11]);

        $list = $model->orderBy($order)
            ->leftJoin('bus_member_consume', 'bus_member_consume.member_id = bus_member.member_id and consume_type != "退款"')
            ->groupBy('bus_member.member_id')
            ->limit($pages->limit)->offset($pages->offset)->asArray()->all();

        // 会员卡类型
        $listGrade = BusConfig::find()->where(['shop_id' => $this->userInfo->shop_id, 'config_type' => 1])->asArray()->all();
        foreach ($listGrade as $key => $grade) {
            $listGrade[$key]['counts'] = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_grade' => $grade['config_key'], 'del_flag' => 1])->count();
        }

        $totalCountMember = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->count();

        return $this->render('index', [
            'list' => $list,
            'page' => $pages,
            'listGrade' => $listGrade,
            'totalCountMember' => $totalCountMember
        ]);
    }

    /**
     * 基本信息
     * @param int $id 会员id
     * @return mixed
     */
    public function actionBasic($id = null)
    {
        if ($id === null) { // 新增
            $model = new BusMember();
            $model->shop_id = $this->userInfo->shop_id;
            $model->boss_id = $this->userInfo->boss_uid;
            $model->last_consume_time = date('Y-m-d H:i:s');
            $model->member_birthday = $model->member_birthday ?: '1980-01-01';
        } else {
            $model = $this->checkMember($id);
        }
        if ($model->load(Yii::$app->request->post())) {
            if (!$model->checkParams()) $this->error($model->errorMessage);

            $model->save(false);

            /*if ($id === null) {
                return $this->redirect(['index']);
            }*/

            Yii::$app->getSession()->setFlash('success', $id === null ? '新增成功' : '修改成功');
            return $this->redirect(['basic', 'id' => $id ?: $model->member_id]);
        }

        return $this->render('basic', [
            'model' => $model
        ]);
    }

    /**
     * 账户信息
     */
    public function actionAccount()
    {
        if (!($id = Yii::$app->getRequest()->get('id', 0))) {
            $this->error('参数错误');
        }

        $BusMember = $this->checkMember($id);

        $model = BusAccount::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_id' => $id]);

        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);

        $model = $model->orderBy('account_id DESC')->limit($pages->limit)->offset($pages->offset)->asArray()->all();

        return $this->render('account', [
            'BusMember' => $BusMember,
            'list' => $model,
            'page' => $pages
        ]);
    }

    /**
     * 体质信息
     */
    public function actionConstitution()
    {
        if (!($id = Yii::$app->getRequest()->get('id', 0))) {
            $this->error('参数错误');
        }

        $BusMember = $this->checkMember($id);
        $arrayHealthId = [14, 28, 42, 47, 52, 62, 78, 89];

        if ($BusMember->load(Yii::$app->request->post())) {
//            echo '<pre>';
//            var_dump($_POST);
//            die;
            $dataList = [];
            $customNameList = [];
            $attrList = isset($_POST['attr_id']) ? $_POST['attr_id'] : [];
            foreach ($attrList as $val) {
                if (in_array($val, $arrayHealthId)) {
                    if (!empty($_POST["custom_name_{$val}"])) {
                        $customNameList[] = [$id, $val, $_POST["custom_name_{$val}"]];
                        $dataList[] = [$id, $val, $this->userInfo->shop_id];
                    }
                } else {
                    $dataList[] = [$id, $val, $this->userInfo->shop_id];
                }
            }

            if (!$BusMember->checkParams()) $this->error($BusMember->errorMessage);

            $BusMember->save(false);

            BusMemberHealth::deleteAll('member_id = ' . $id);
            \common\models\BusHealthCustom::deleteAll('member_id = ' . $id);

            if ($dataList) {
                Yii::$app->db->createCommand()->batchInsert('bus_member_health', [
                    'member_id', 'attr_id', 'shop_id'
                ], $dataList)->execute();
            }
            if ($customNameList) {
                Yii::$app->db->createCommand()->batchInsert('bus_health_custom', [
                    'member_id', 'health_id', 'health_name'
                ], $customNameList)->execute();
            }

            Yii::$app->session->setFlash('success', '1');

            return $this->redirect(['constitution', 'id' => $id]);
        }

        // 会员的体质信息
        $memberHealthList = BusMemberHealth::find()->where(['member_id' => $id])->asArray()->all();
        $memberHealthListId = [];
        foreach ($memberHealthList as $val) {
            $memberHealthListId[] = $val['attr_id'];
        }

        // 体质信息数据
        $BusHealth = new BusHealth();
        $healthList = $BusHealth->getAll();

        return $this->render('constitution', [
            'memberHealthListId' => $memberHealthListId,
            'healthList' => $healthList,
            'BusHealth' => $BusHealth,
            'BusMember' => $BusMember,
            'arrayHealthId' => $arrayHealthId
        ]);
    }

    /**
     * 服务记录
     */
    public function actionServer()
    {
        if (!($id = Yii::$app->getRequest()->get('id', 0))) {
            $this->error('参数错误');
        }

        // 疗程卡列表
        $beautycardList = BusMemberBeautycard::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_id' => $id])->andWhere(['!=', 'remain_times', 0])->orderBy('card_id')->asArray()->all();

        // 服务记录列表
        $BusService = BusService::find()->where(['service_member_id' => $id, 'shop_id' => $this->userInfo->shop_id, 'service_status' => 2]);
        $totalCount = $BusService->count();
        $pages = new Pagination(['totalCount' => $totalCount, 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);
        $list = $BusService->orderBy('service_id DESC')->limit($pages->limit)->offset($pages->offset)->with('extends')->asArray()->all();

        return $this->render('server', [
            'beautycardList' => $beautycardList,
            'list' => $list,
            'page' => $pages,
            'totalCount' => $totalCount
        ]);
    }

    /**
     * 消费记录
     */
    public function actionConsume()
    {
        if (!($id = Yii::$app->getRequest()->get('id', 0))) {
            $this->error('参数错误');
        }
        $BusMember = $this->checkMember($id);

        $model = BusMemberConsume::find()->where(['shop_id' => $this->userInfo->shop_id, 'member_id' => $id])->andWhere(['!=', 'consume_type', '缴欠款'])->andWhere(['!=', 'consume_type', '退款']);
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $this->pageNavLimit, 'defaultPageSize' => $this->pageNavLimit]);

        $list = $model->orderBy('consume_time DESC')->limit($pages->limit)->offset($pages->offset)->asArray()->all();

        return $this->render('consume', [
            'list' => $list,
            'BusMember' => $BusMember,
            'page' => $pages
        ]);
    }

    /**
     * 会员分析
     */
    public function actionAnalysis($key = '', $sort = 'dft')
    {
        switch ($sort) {
            case 'counts': // 到店次数
                $sort = 'consume_counts DESC';
                break;
            case 'consume':
                $sort = 'consume_count DESC';
                break;
            default:
                $sort = 'member_id';
        }
        $pageSize = 10;

        $model = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1]);

        if ($key) {
            $model->andWhere(['like', 'member_name', $key]);
        }

        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

        $list = $model->orderBy($sort)->limit($pages->limit)->offset($pages->offset)->asArray()->all();

        $totalCount = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->count();
        $count2 = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->andWhere(['>=', '(consume_count/consume_counts)', 500])->andWhere(['<=', '(consume_count/consume_counts)', 1000])->count();

        $count3 = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->andWhere(['>=', '(consume_count/consume_counts)', 1001])->andWhere(['<=', '(consume_count/consume_counts)', 1500])->count();

        $count4 = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->andWhere(['>=', '(consume_count/consume_counts)', 1501])->andWhere(['<=', '(consume_count/consume_counts)', 2000])->count();

        $count5 = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->andWhere(['>=', '(consume_count/consume_counts)', 2001])->andWhere(['<=', '(consume_count/consume_counts)', 2500])->count();

        $count6 = BusMember::find()->where(['shop_id' => $this->userInfo->shop_id, 'del_flag' => 1])->andWhere(['>', '(consume_count/consume_counts)', 2500])->count();
        $count1 = $totalCount - $count2 - $count3 - $count4 - $count5 - $count6;

        if ($totalCount > 0) {
            $datas = [
                ['count' => $count1, 'ratio' => round($count1 / $totalCount, 4) * 100],
                ['count' => $count2, 'ratio' => round($count2 / $totalCount, 4) * 100],
                ['count' => $count3, 'ratio' => round($count3 / $totalCount, 4) * 100],
                ['count' => $count4, 'ratio' => round($count4 / $totalCount, 4) * 100],
                ['count' => $count5, 'ratio' => round($count5 / $totalCount, 4) * 100],
                ['count' => $count6, 'ratio' => round($count6 / $totalCount, 4) * 100],
            ];
        } else {
            $datas = [
                ['count' => $count1, 'ratio' => 0],
                ['count' => $count2, 'ratio' => 0],
                ['count' => $count3, 'ratio' => 0],
                ['count' => $count4, 'ratio' => 0],
                ['count' => $count5, 'ratio' => 0],
                ['count' => $count6, 'ratio' => 0],
            ];
        }

        return $this->render('analysis', [
            'page' => $pages,
            'list' => $list,
            'datas' => $datas
        ]);
    }

    /**
     * 添加会员的疗程卡
     */
    public function actionBeautycard($id, $key = '')
    {
        $this->layout = '/alert';

        if (Yii::$app->request->isPost) {

            if (($member_id = Yii::$app->getRequest()->post('member_id')) == null) {
                $this->error('会员id错现错误');
            }

            $dataList = [];
            $date = date('Y-m-d H:i:s');

            $busBeautycardMemoryList = BusBeautycardMemory::find()->where(['member_id' => $member_id])->asArray()->all();

            foreach ($busBeautycardMemoryList as $beautyCard) {
                $dataList[] = [
                    $beautyCard['beauty_card'], $beautyCard['total_count'], $beautyCard['available_count'],
                    $date, $member_id, $this->userInfo->shop_id,
                    $this->userInfo->boss_uid, $beautyCard['total_price'], $beautyCard['total_price'] == 0 ? 1 : 0
                ];
            }

            if ($dataList) {
                $result = Yii::$app->db->createCommand()->batchInsert('bus_member_beautycard', [
                    'card_name', 'total_times', 'remain_times',
                    'create_time', 'member_id', 'shop_id',
                    'boss_id', 'total_price', 'is_give'
                ], $dataList)->execute();

                if ($result) {
                    BusBeautycardMemory::deleteAll(['member_id' => $member_id]);
                }
            }

            exit( "<script>top.location.href='" . Url::to(['server', 'id' => $member_id]) . "'</script>" );
        }

        // 店铺的疗程卡
        $pageSize = 10;
        $totalCount = Yii::$app->db->createCommand("SELECT COUNT(*) c FROM bus_config c LEFT JOIN bus_beautycard_memory b ON c.config_id = b.beautycard_id AND b.member_id = {$id} WHERE c.config_type = 2 AND c.shop_id = {$this->userInfo->shop_id} AND c.config_key LIKE '%{$key}%'")->queryOne();

        $pages = new Pagination(['totalCount' => $totalCount['c'], 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

        $beautyCardList = Yii::$app->db->createCommand("SELECT c.*, b.beautycard_id, b.available_count, b.total_price FROM bus_config c LEFT JOIN bus_beautycard_memory b ON c.config_id = b.beautycard_id AND b.member_id = {$id} WHERE c.config_type = 2 AND c.shop_id = {$this->userInfo->shop_id} AND c.config_key LIKE '%{$key}%' LIMIT {$pages->offset},{$pages->limit}")->queryAll();

        $beautyCardListAll = Yii::$app->db->createCommand("SELECT c.*, b.beautycard_id, b.available_count FROM bus_config c LEFT JOIN bus_beautycard_memory b ON c.config_id = b.beautycard_id AND b.member_id = {$id} WHERE c.config_type = 2 AND c.shop_id = {$this->userInfo->shop_id} AND c.config_key LIKE '%{$key}%'")->queryAll();

        return $this->render('beautycard', [
            'beautyCardList' => $beautyCardList,
            'beautyCardListAll' => $beautyCardListAll,
            'page' => $pages
        ]);
    }

    /**
     * 检查会员的合法性
     * @param int $member_id 会员id
     * @return mixed
     */
    public function checkMember($member_id)
    {
        if (($BusMember = BusMember::findOne(['del_flag' => 1, 'member_id' => $member_id, 'shop_id' => $this->userInfo->shop_id])) !== null) {
            return $BusMember;
        } else {
            $this->error('会员不存在');
        }
    }

    /**
     * 增加会员的临时疗程卡
     * @param int $beautycard_id 疗程卡id
     * @param string $beauty_card 疗程卡名称
     * @param int $member_id 会员id
     * @param int $total_count 总使用次数
     * @param int $available_count 可用次数
     * @param boolean $type true增加， false删除
     */
    public function actionAddbeautycard($beautycard_id, $beauty_card, $member_id, $total_count = 0, $available_count = 0, $type = true)
    {
        $request = Yii::$app->getRequest();
        if ($request->isAjax) {
            if ($type) {
                $result = Yii::$app->db->createCommand()->insert('bus_beautycard_memory', [
                    'beautycard_id' => $beautycard_id,
                    'beauty_card' => $beauty_card,
                    'member_id' => $member_id,
                    'total_count' => $total_count,
                    'available_count' => $available_count,
                    'total_price' => $request->get('total_price', '0') ?: '0'
                ])->execute();

                echo $result ? '1' : '0';
            } else { // 删除
                $result = Yii::$app->db->createCommand()->delete('bus_beautycard_memory', [
                    'beautycard_id' => $beautycard_id,
                    'member_id' => $member_id,
                ])->execute();
                echo $result ? '1' : '0';
            }
        }
    }

    /**
     * 修改疗程卡的可用次数
     * @param int $beautycard_id 疗程卡id
     * @param int $member_id 会员id
     * @param int $available_count 可用次数
     */
    public function actionSetbeautycard($beautycard_id, $member_id, $available_count = 0, $total_price = 0)
    {
        if (!is_numeric($available_count) || $available_count < 0) {
            exit('0');
        }
        $result = Yii::$app->db->createCommand()->update('bus_beautycard_memory', [
            'available_count' => $available_count,
            'total_price' => $total_price
        ], [
            'beautycard_id' => $beautycard_id,
            'member_id' => $member_id,
        ])->execute();

        echo $result === false ? '0' : '1';
    }

    /**
     * 作废会员
     */
    public function actionDeletemember()
    {
        $request = Yii::$app->getRequest();
        if ($request->isAjax && ($member_id = $request->get('member_id'))) {
            $count = BusMember::updateAll(['del_flag' => -1], [
                'member_id' => $member_id,
                'shop_id' => $this->userInfo->shop_id
            ]);
            echo $count ? '1' : '0';
        }
    }

    /**
     * 导出会员的信息
     */
    public function actionExcel($key = '', $type = '', $sort = '')
    {
        //创建一个excel
        $objPHPExcel = new \PHPExcel();
        //创建新的内置表
        $objPHPExcel->createSheet();
        //设置活动sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //获取当前活动sheet
        $objSheet = $objPHPExcel->getActiveSheet();
        //设置title
        $objSheet->setCellValue('A1','姓名')->setCellValue('B1','电话')
            ->setCellValue('C1','会员类型')->setCellValue('D1','生日')
            ->setCellValue('E1','地址')->setCellValue('F1','职业')
            ->setCellValue('G1','婚姻')->setCellValue('H1','储值卡')
            ->setCellValue('I1','欠款')->setCellValue('J1','累计消费')
            ->setCellValue('K1','未到店时间');

        $where = '';
        if ($key) { // 会员名、手机号码检索
            if (is_numeric($key)) {
                $where = " AND bus_member.member_mobile like '%{$key}%'";
            } else {
                $where = " AND bus_member.member_name like '%{$key}%'";
            }
        }
        if ($type && $type != 'all') { // 会员类型检索
            $where .= " AND bus_member.member_grade = '{$type}'";
        }
        switch ($sort) { // 排序方式
            case 'consume':
                $order = 'consume_amount_all DESC';
                break;
            case 'last':
                $order = 'bus_member.last_consume_time';
                break;
            default:
                $order = 'bus_member.member_id';
        }
        //获取数据
        $listData = Yii::$app->db->createCommand('SELECT bus_member.*, (SUM(cash_pay) + SUM(unionpay)) consume_amount_all FROM bus_member LEFT JOIN bus_member_consume ON bus_member_consume.member_id = bus_member.member_id AND consume_type != "退款"WHERE bus_member.shop_id = '. $this->userInfo->shop_id .' AND del_flag = 1'. $where .' GROUP BY bus_member.member_id ORDER BY ' . $order)->queryAll();

        $i = 2;
        foreach ($listData as $k => $v){
            $last_consume_time = floor((time() - strtotime($v['last_consume_time'])) / 86400);
            $objSheet->setCellValue('A'.$i,$v['member_name'])->setCellValue('B'.$i,$v['member_mobile'])
                ->setCellValue('C'.$i,$v['member_grade'])->setCellValue('D'.$i,$v['member_birthday'])
                ->setCellValue('E'.$i,$v['address'])->setCellValue('F'.$i,$v['member_job'])
                ->setCellValue('G'.$i,$v['marriage'] ? '已婚' : '未婚')->setCellValue('H'.$i,$v['member_balance'])
                ->setCellValue('I'.$i,$v['member_debt'])->setCellValue('J'.$i,$v['consume_amount_all'])
                ->setCellValue('K'.$i,$last_consume_time);
            $i++;
        }
        \common\extended\system\Util::browser_export('Excel5','member.xls');//输出到浏览器
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save("php://output");
    }

    public function actionDatetime()
    {
        $this->layout = '/alert';
        return $this->render('datetime');
    }
}
